<template>
 
        <div class="header-controls">
          <el-button  type="primary" @click="initDicom"> 初始化</el-button>

          <el-input v-model="studyInstanceUid" placeholder="请输入检查实例UID" style="width: 300px; margin-right: 10px;"
            disabled />
          <el-select v-model="seriesInstanceUid" placeholder="请选择序列实例" style="width: 300px; margin-right: 10px;">
            <el-option v-for="series in seriesInstanceUidOptions" :key="series.seriseId"
              :label="series.seriseId" :value="series.seriseId" />
          </el-select>

          <el-button type="primary" @click="loadDicomViewer" >
            加载影像
          </el-button>
        </div>

        <!-- DICOM图像显示区域 -->
        <div id="dicom-viewport1" class="viewport"></div>

        <div id="dicom-viewport2"></div>
   
</template>

<script setup>
import { useRoute } from 'vue-router';
import { getSeriseAllList } from "@/api/pacs/serise/serise"
import { DicomDataService } from '@/api/pacs/dicom/dicomService.js'
import {getSeriesImages} from '@/api/pacs/dicom/dicom.js'

import {
  createQiniuImageIds
} from "@/utils/dicom/dicom";


import {
  Enums,
  RenderingEngine,
  imageLoader,
  volumeLoader,
  setVolumesForViewports,
  init as coreInit
} from '@cornerstonejs/core'

import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'
import { onMounted } from "vue";

const { ViewportType } = Enums;
const route = useRoute();
// 创建DicomDataService实例
const dicomService = new DicomDataService();


const studyId = ref() //studyID
const studyInstanceUid = ref('')  //studyUId
const seriesInstanceUid = ref('') //Series UID
const seriesInstanceUidOptions = ref([])
let imageIds=ref([])


// 视图DOM引用
const viewport1Ref = ref(null)
const viewport2Ref = ref(null)

/***
 *  ViewPort 和 renderingEngine
 */

const viewportId1 = 'CT_AXIAL';
const viewportId2 = 'CT_SAGITTAL';

 const volumeId = 'myVolume';

let renderingEngineId = 'myRenderingEngine'
let viewPort1 = null
let viewPort2 = null
let renderingEngine = null


onMounted(async () => {
    studyId.value = route.query.studyId;
  
     if (studyId.value && studyId.value.trim() !== '') {
     
          fetchSeriesList();
    }
})

/***
 * 通过StudyId，获取序列列表
*/
const fetchSeriesList = async () => {
  seriesInstanceUidOptions.value = [] //为了方便遍历
  seriesInstanceUid.value = ''
    // 调用后端API获取序列列表
    const response = await getSeriseAllList({studyId: studyId.value})
    seriesInstanceUidOptions.value = response.data || []
 
}


/***
 * 显示Dicom图像
 */

const loadDicomViewer = async () => {


    const series = await getSeriesImages(studyId.value, seriesInstanceUid.value);
   
    const tempImageIds = series.data.images;

    
    

      //把imageIds 进行协议封装
    const _imageIds=createQiniuImageIds(tempImageIds);
    
    console.log("imageIDs",_imageIds);
    
    imageIds.value=_imageIds;

    
    //注册七牛云加载器
    registerQiniuImageLoader();

    console.log(imageIds.value);


    if(renderingEngine==null){
      console.log("renderingEngine 为Null");
      return;
    }
    //获取Volume
    const volume = await volumeLoader.createAndCacheVolume(volumeId, {
        imageIds,
    });
    //    加载Volume
    volume.load();

    setVolumesForViewports(
        renderingEngine,
        [{ volumeId }],
        [viewportId1, viewportId2]
    );

    console.log("======End============")
   
}


function registerQiniuImageLoader(){
  imageLoader.registerImageLoader('qiniu', (imageId) => {
    const promise = (async () => {
            try {
                // 解析图像ID，把标志去掉
                const url = imageId.replace('qiniu:', '').split('?')[0]
                console.log("===url=========",url);

                // 从七牛云获取DICOM数据
                // const arrayBuffer = await dicomService.fetchDicomDataFromQiniu(url);

                const arrayBuffer = await dicomService.fetchDicomFromQiniu(url)
            
                // 使用DICOM图像加载器处理数据
                const dicomImageLoader = cornerstoneDICOMImageLoader.wadouri.loadImage
                
                // 创建临时的wadouri格式imageId
                const blob = new Blob([arrayBuffer], { type: 'application/dicom' })
                const blobUrl = URL.createObjectURL(blob)
                const wadouriImageId = `wadouri:${blobUrl}`
                console.log("输出wadouri",wadouriImageId);
              
                // 调用原始的DICOM加载器
                const imageLoadObject = dicomImageLoader(wadouriImageId)
                console.log("imageLoadObject",imageLoadObject);
                // 等待图像加载完成
                const image = await imageLoadObject.promise
                console.log('图像加载成功:', image)
                
                // 清理临时URL
                URL.revokeObjectURL(blobUrl)
                
                return image
                
            } catch (error) {
                console.error('七牛云图像加载失败:', {
                    imageId,
                    error: error.message,
                    stack: error.stack
                })
                throw error
            }
        })()

    return {
      promise,
      cancelFn: () => {
        console.log('取消图像加载');
      }
    };
  });
}
/**
 * 注册七牛云图像加载器
 */
function registerQiniuImageLoaderA() {

  
  imageLoader.registerImageLoader('qiniu', (imageId) => {
    const loadPromise = new Promise(async (resolve, reject) => {
      try {
        const url = imageId.replace('qiniu:', '');
        

        console.log('开始加载七牛云图像:', url);
        const arrayBuffer = await dicomService.fetchDicomDataFromQiniu(url);

  
        // 使用wadouri加载器
        const blob = new Blob([arrayBuffer], { type: 'application/dicom' });
        const blobUrl = URL.createObjectURL(blob);
        const wadUriImageId = `wadouri:${blobUrl}`;
        
        console.log('使用wadouri加载器，临时imageId:', wadUriImageId);
        
        try {
          const dicomImageLoader = cornerstoneDICOMImageLoader.wadouri.loadImage;
      
          const imageLoadObject=dicomImageLoader(wadUriImageId);

          console.log("imageLoadObject",imageLoadObject);
         
          const image = await imageLoadObject.promise;

          console.log('通过wadouri加载器加载成功',image);
        
          
          URL.revokeObjectURL(blobUrl);
          
          return image;

        } catch (wadoError) {
       
          console.error('wadouri加载器失败:', wadoError);
          URL.revokeObjectURL(blobUrl);
          reject(wadoError);
        }

      } catch (error) {
        console.error('七牛云图像加载失败:', error);
        reject(error);
      }
    });

    return {
      promise: loadPromise,
      cancelFn: () => {
        console.log('取消图像加载');
      }
    };
  });
}
/**
 * 初始化组件
 */
const initDicom=async()=>{
    viewport1Ref.value=document.getElementById("dicom-viewport1");
    viewport2Ref.value=document.getElementById("dicom-viewport2");
    console.log("====初始化开始====");

    await coreInit();
    await cornerstoneDICOMImageLoader.init();

    const tempRenderingEngine = new RenderingEngine(renderingEngineId);

    const viewportInput = [
        {
            viewportId: viewportId1,
            element: viewport1Ref.value,
            type: ViewportType.ORTHOGRAPHIC,
            defaultOptions: {
            orientation: Enums.OrientationAxis.AXIAL,
            },
        },
        {
            viewportId: viewportId2,
            element: viewport2Ref.value,
            type: ViewportType.ORTHOGRAPHIC,
            defaultOptions: {
            orientation: Enums.OrientationAxis.SAGITTAL,
            },
        },
    ];

    
    tempRenderingEngine.setViewports(viewportInput);

    renderingEngine=tempRenderingEngine;
    console.log("====初始化完成====")


}


</script>
<style scoped>
  .viewport {
            width: 800px;
            height: 800px;
          
            margin-top: 20px;
            margin-left: 20px;
          
            background-color: black;
  }
</style>